package com.example.demo.service.Impl;

import cn.idev.excel.ExcelWriter;
import com.example.demo.service.IExcelService;
import com.example.demo.vo.ExcelUserVo;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelService implements IExcelService {

    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户数据.xlsx", StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        // 模拟数据
        List<ExcelUserVo> userList = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            userList.add(new ExcelUserVo(i, "测试"));
        }

        // 使用fastexcel导出
//            OutputStream os = response.getOutputStream();
//            ExcelWriter writer = new ExcelWriter(os);
//            writer.writeSheetHeader("用户表", new String[]{"ID", "姓名", "年龄", "创建时间"});
//            for (ExcelUserVo user : userList) {
//                writer.writeSheetRow(new Object[]{
//                        user.getId(),
//                        user.getName(),
//                });
//            }
    }

    @Override
    public List<ExcelUserVo> importExcel(MultipartFile file) {
        List<ExcelUserVo> userList = new ArrayList<>();

//        try (InputStream is = file.getInputStream()) {
//            ExcelReader reader = new ExcelReader(is);
//            reader.readSheet(0, new RowHandler() {
//                @Override
//                public void handle(int rowIndex, List<Object> rowList) {
//                    // 跳过表头
//                    if (rowIndex == 0) {
//                        return;
//                    }
//                    User user = new User();
//                    user.setId(Long.valueOf(rowList.get(0).toString()));
//                    user.setName(rowList.get(1).toString());
//                    user.setAge(Integer.valueOf(rowList.get(2).toString()));
//                    user.setCreateTime((Date) rowList.get(3));
//                    userList.add(user);
//                }
//            });
//        }

        return userList;
    }
}
